package com.liu.network.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class SocketService3 {
	// 搭建服务器端
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(56789);
		Socket client = server.accept();
		InputStream is = null;
		OutputStream os = null;
		boolean b =true;
		while(b){
			client = server.accept();
			is = client.getInputStream();
			int r = 0;
			List<Byte> list = new LinkedList<Byte>();
			while ((r = is.read()) != -1) {
				list.add(Byte.valueOf((byte) r));
			}
			byte[] data = new byte[list.size()];
			for (int i = 0; i < list.size(); i++) {
				data[i] = list.get(i);
			}
			String str = new String(data);
			System.out.println("客户端传输过来的参数" + str);
			
			os = client.getOutputStream();
			
		}
	}

	public void server() {
		try {
			// 指定绑定的端口，并监听此端口。
			ServerSocket server = new ServerSocket(56789);
			System.out.println("服务器启动成功");
			// 调用accept()方法开始监听，等待客户端的连接
			// 使用accept()阻塞等待客户请求，有客户
			// 请求到来则产生一个Socket对象，并继续执行
			Socket socket = server.accept();

			// 接受客户端数据
			InputStream is = socket.getInputStream();
			int r = 0;
			List<Byte> list = new LinkedList<Byte>();
			while ((r = is.read()) != -1) {
				list.add(Byte.valueOf((byte) r));
			}
			byte[] data = new byte[list.size()];
			for (int i = 0; i < list.size(); i++) {
				data[i] = list.get(i);
			}
			String str = new String(data);
			System.out.println("客户端传输过来的参数" + str);

			// 返回数据到客户端
			// List<Byte> head = new LinkedList<Byte>();
			byte[] a = hexStringToByteArray("464E4951");
			byte[] b = new byte[4];
			String response = "status:1,err_msg:Can not find %s, white list function is invaliable!";
			byte[] c = response.getBytes();
			b = (c.length + "").getBytes();
			byte[] head = new byte[4 + 4 + c.length];
			for (int i = 0; i < a.length; i++) {
				head[i] = a[i];
				// head.add(a[i]);
			}
			for (int i = 0; i < b.length; i++) {
				head[i + 4] = b[i];
				// head.add(b[i]);
			}
			for (int i = 0; i < c.length; i++) {
				head[i + 8] = c[i];
				// head.add(c[i]);
			}
			OutputStream os = socket.getOutputStream();
			// 关闭连接
			os.write(head);
			os.close();
			is.close();
			socket.close(); // 关闭Socket
			server.close(); // 关闭ServerSocket
		} catch (Exception e) {
			System.out.println("Error." + e);
		}
	}

	public static byte[] hexStringToByteArray(String hexStr) {
		if (hexStr.length() % 2 == 1) {
			hexStr = "0" + hexStr;
		}
		int len = hexStr.length() / 2;
		byte[] result = new byte[len];
		char[] chars = hexStr.toCharArray();
		for (int i = 0; i < len; i++) {
			result[i] = (byte) (charToByte(chars[i]) << 4 | charToByte(chars[i + 1]));
		}
		return result;
	}

	private static int charToByte(char c) {
		String chars = "0123456789ABCDEF";
		byte b = (byte) chars.indexOf(c);
		return b;
	}

}